package com.zhengjiang.serialport;

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 串口通信
 */
public class ComTest {
    private Map<String, SerialPort> comMap = new HashMap<String, SerialPort>();
    private List<String> comList = new ArrayList<>();

    public ComTest() {
        //将所有的串口信息放入comlist,comMap中
        SerialPort[] commPorts = SerialPort.getCommPorts();
        for (SerialPort commPort : commPorts) {
            comList.add(commPort.getSystemPortName());
            comMap.put(commPort.getSystemPortName(), commPort);
            //监听所有串口通信的数据
            commPort.openPort();
            commPort.addDataListener(new SerialPortDataListener() {
                @Override
                public int getListeningEvents() {
                    return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
                }

                @Override
                public void serialEvent(SerialPortEvent serialPortEvent) {
                    byte[] newData = serialPortEvent.getReceivedData();
                    System.err.println(String.format("串口%s接收到数据大小：%s,串口数据内容:%s"
                            , serialPortEvent.getSerialPort().getSystemPortName(), newData.length, new String(newData)));
                }
            });
        }
    }

    public static void main(String[] args) {
        ComTest comTest = new ComTest();
        List<String> comList = comTest.comList;
        Map<String,SerialPort> comMap = comTest.comMap;
        System.out.println(comList);
        System.out.println(comMap);
    }


}
